<template>
  <div class="container">
    <Breadcrumb :items="['menu.articleManage', 'menu.article']" />
    <a-card class="custom-card" title="">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="query"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-align="left"
          >
            <a-row :gutter="16">
              <a-col :span="6">
                <a-input v-model="query.name" placeholder="请输入名称" allow-clear>
                  <template #prepend>名称</template>
                </a-input>
              </a-col>
              <a-col :span="6">
                <a-cascader
                  v-model="query.cate_ids"
                  :options="categoryDatas"
                  :field-names="{ value: 'id', label: 'name' }"
                  :max-tag-count="1"
                  placeholder="分类"
                  multiple
                  check-strictly
                  allow-search
                  allow-clear
                  @change="pickCategoryQuery"
                />
              </a-col>
              <a-col :span="9">
                <a-input-group>
                  <a-select v-model="query.time_type" placeholder="时间类型" :style="{width:'120px'}">
                    <a-option value="created_at" label="添加时间" />
                  </a-select>
                  <a-range-picker v-model="query.range_date" allow-clear/>
                </a-input-group>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 44px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space :size="18">
            <a-button type="primary" @click="search">
              <template #icon><icon-search /></template>搜索
            </a-button>
            <a-button status="success" @click="refresh()">
              <template #icon><icon-refresh /></template>重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space>
            <a-button type="primary" status="danger" @click="batchDel()">
              <template #icon><icon-delete /></template>批量删除
            </a-button>
            <a-button type="primary" @click="add()">
              <template #icon><icon-plus /></template>
              <template #default>添加</template>
            </a-button>
          </a-space>
        </a-col>
        <a-col :span="12" style="display: flex; align-items: center; justify-content: end">
          <a-tooltip content="刷新">
            <div class="action-icon" @click="refresh"><icon-refresh size="18"/></div>
          </a-tooltip>
          <a-dropdown @select="handleSelectDensity">
            <a-tooltip content="密度">
              <div class="action-icon"><icon-line-height size="18"/></div>
            </a-tooltip>
            <template #content>
              <a-doption v-for="item in densityList" :key="item.value" :value="item.value" :class="{ active: item.value === size }">
                <span>{{ item.name }}</span>
              </a-doption>
            </template>
          </a-dropdown>
          <a-tooltip content="列设置">
            <a-popover trigger="click" position="bl" @popup-visible-change="popupVisibleChange">
              <div class="action-icon"><icon-settings size="18" /></div>
              <template #content>
                <div id="tableSetting">
                  <div v-for="(item, index) in showColumns" :key="item.dataIndex" class="setting">
                    <div style="margin-right: 4px; cursor: move">
                      <icon-drag-arrow />
                    </div>
                    <div>
                      <a-checkbox v-model="item.checked" @change="handleChangeColumn($event, item as TableColumnData, index)"></a-checkbox>
                    </div>
                    <div class="title">
                      {{ item.title === '#' ? '序列号' : item.title }}
                    </div>
                  </div>
                </div>
              </template>
            </a-popover>
          </a-tooltip>
        </a-col>
      </a-row>
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        :columns="(cloneColumns as TableColumnData[])"
        :data="renderData"
        :size="size"
        :bordered="{ wrapper: true, cell: true }"
        :row-selection="rowSelection"
        :scroll="tableScroll"
        column-resizable
        @selection-change="selectionChange"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #coverImg="{ record }">
<!--          <a-image v-if="record.full_cover_img" :src="record.full_cover_img" :preview="false" @click="preview" width="40" height="40"/>-->
          <a-image v-if="record.full_cover_img" :src="record.full_cover_img" width="40" height="40"/>
        </template>
        <template #status="{ record }">
          <a-tag :color="statusFilter[record.status]">{{ record.status_name }}</a-tag>
        </template>
        <template #operations="{ record }">
          <a-space>
            <a-button type="primary" size="small" @click="add(record)"><template #icon><icon-edit /></template>编辑</a-button>
            <a-button type="primary" status="danger" size="small" @click="del([record])"><template #icon><icon-delete /></template>删除</a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <Detail
      ref="detailRef"
      :categoryDatas="categoryDatas"
      @saveCallback="fetchData"
    />

    <a-image-preview-group
      v-model:visible="coverImgVisible"
      v-model:current="coverImgCurrent"
      infinite
      :srcList="coverImgList"
    />
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive, h, compile, watch, nextTick } from 'vue';
  import { useI18n } from 'vue-i18n';
  import { Message, Modal } from '@arco-design/web-vue';
  // import type { SelectOptionData } from '@arco-design/web-vue/es/select/interface';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import cloneDeep from 'lodash/cloneDeep';
  import Sortable from 'sortablejs';

  import useLoading from '@/hooks/loading';
  import screenHeight from '@/utils/screen-height';
  import { Pagination } from '@/types/global';
  import { DataState, QueryParams, apiList, apiDel, apiCateList } from '@/api/article';
  import Detail from './components/detail.vue';

  type SizeProps = 'mini' | 'small' | 'medium' | 'large';
  type Column = TableColumnData & { checked?: true };

  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const height = screenHeight(370);
  const basePagination: Pagination = {
    current: 1,
    pageSize: 20,
    showTotal: true,
    showJumper: true,
    showPageSize: true,
    pageSizeOptions: [10, 20, 30, 50, 100, 150, 200, 300, 500],
  };
  const baseQuery = () => {
    return {
      page: 1,
      limit: 20,
      name: '',
      cate_ids: [],
      time_type: 'created_at',
      range_date: [],
    };
  };
  const cloneColumns = ref<Column[]>([]);
  const showColumns = ref<Column[]>([]);

  const columns = computed<TableColumnData[]>(() => [
    {
      title: 'ID', dataIndex: 'id', width: 60,
      align: 'center' as 'left' | 'right' | 'center',
      fixed: 'left' as 'left' | 'right',
      sortable: {sortDirections: ['ascend', 'descend'] as ('ascend' | 'descend')[]},
    },
    {
      title: '封面图', dataIndex: 'cover_img', width: 80,
      align: 'center' as 'left' | 'right' | 'center',
      slotName: 'coverImg',
    },
    {
      title: '标题', dataIndex: 'title', width: 160,
      align: 'center' as 'left' | 'right' | 'center',
    },
    {
      title: '分类', dataIndex: 'cate_name', width: 160,
      align: 'center' as 'left' | 'right' | 'center',
    },
    {
      title: '状态', dataIndex: 'status', width: 120,
      align: 'center' as 'left' | 'right' | 'center',
      slotName: 'status',
    },
    {
      title: '排序', dataIndex: 'sorting', width: 80,
      align: 'center' as 'left' | 'right' | 'center',
    },
    {
      title: '创建时间', dataIndex: 'created_at', width: 180,
      align: 'center' as 'left' | 'right' | 'center',
      sortable: {sortDirections: ['ascend', 'descend'] as ('ascend' | 'descend')[]},
    },
    {
      title: '操作', dataIndex: 'operations', width: 200,
      align: 'center' as 'left' | 'right' | 'center',
      fixed: 'right' as 'left' | 'right',
      slotName: 'operations',
    },
  ]);
  const renderData = ref<DataState[]>([]);
  const query = ref(baseQuery());
  const pagination = reactive({
    ...basePagination,
  });
  const size = ref<SizeProps>('medium');
  const rowSelection = reactive({
    type: 'checkbox' as const,
    showCheckedAll: true,
  });
  const tableScroll = ref({
    x: '100%',
    y: height,
  });
  const statusFilter: any = {
    1: '#00b42a',
    2: '#eb0aa4',
    90: '#ff5722',
  };
  // table 密度
  const densityList = computed(() => [
    {
      name: '迷你',
      value: 'mini',
    },
    {
      name: '偏小',
      value: 'small',
    },
    {
      name: '中等',
      value: 'medium',
    },
    {
      name: '偏大',
      value: 'large',
    },
  ]);

  let selectionKeys: string[] = []; // 选中项ID
  const detailRef = ref();

  const categoryDatas = ref([]); // 分类
  const coverImgVisible = ref(false);
  const coverImgCurrent = ref(1);
  const coverImgList = ref<any>([]);

  watch(
    () => columns.value,
    (val) => {
      cloneColumns.value = cloneDeep(val);
      cloneColumns.value.forEach((item, index) => {
        item.checked = true;
      });
      showColumns.value = cloneDeep(cloneColumns.value);
    },
    { deep: true, immediate: true }
  );

  // 分页
  const onPageChange = (page: number) => {
    fetchData({ ...query.value, page });
  };
  const onPageSizeChange = (limit: number) => {
    fetchData({ ...query.value, limit });
  };
  // 列表
  const fetchData = async (
    params: QueryParams = { page: 1, limit: 20 }
  ) => {
    setLoading(true);
    try {
      const { data } = await apiList(params);
      renderData.value = data.data;
      query.value.page = params.page;
      query.value.limit = params.limit;
      pagination.current = params.page;
      pagination.pageSize = params.limit;
      pagination.total = data.total;

      data.data.forEach((item: any) => {
        coverImgList.value.push(item.full_cover_img);
      });
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };
  // 添加/编辑
  const add = (row?: any) => {
    detailRef.value.fetchData(row);
  };
  // 删除
  const del = (row: any[]) => {
    if (!row.length) {
      selectMsg();
    } else {
      let title = '删除';
      let message = `确定要删除选中的 <span style="color:red">${row.length} </span> 条数据吗？`;
      let ids = row;
      if (row.length === 1 && row[0].id) {
        title = `${title}ID：${row[0].id}`;
        message = `确定要删除 <span style="color:red">${row[0].title} </span> 这条数据吗？`;
        ids = [row[0].id];
      }
      Modal.warning({
        title,
        content: () => h(compile(message)),
        closable: true,
        hideCancel: false,
        onOk: (async () => {
          setLoading(true);
          try {
            await apiDel({ids});
          } catch (err) {
            setLoading(false);
          } finally {
            fetchData({...query.value});
            setLoading(false);
          }
        }),
      });
    }
  };
  // 搜索
  const search = () => {
    query.value.page = 1;
    fetchData({...query.value} as unknown as QueryParams);
  };
  // 刷新
  const refresh = () => {
    query.value = baseQuery();
    fetchData({...query.value});
  };
  const getCategory = async () => {
    const {data} = await apiCateList();
    categoryDatas.value = data.data;
  };
  // 分类选择 -- 查询
  const pickCategoryQuery = () => {
    //
  };

  // 选择 table 密度
  const handleSelectDensity = (
    val: string | number | Record<string, any> | undefined,
    e: Event
  ) => {
    size.value = val as SizeProps;
  };
  // table 列配置
  const handleChangeColumn = (
    checked: boolean | (string | boolean | number)[],
    column: Column,
    index: number
  ) => {
    if (!checked) {
      cloneColumns.value = showColumns.value.filter(
        (item) => item.dataIndex !== column.dataIndex
      );
    } else {
      cloneColumns.value.splice(index, 0, column);
    }
  };
  const exchangeArray = <T extends Array<any>>(
    array: T,
    beforeIdx: number,
    newIdx: number,
    isDeep = false
  ): T => {
    const newArray = isDeep ? cloneDeep(array) : array;
    if (beforeIdx > -1 && newIdx > -1) {
      // 先替换后面的，然后拿到替换的结果替换前面的
      newArray.splice(beforeIdx, 1, newArray.splice(newIdx, 1, newArray[beforeIdx]).pop());
    }
    return newArray;
  };
  // 文字气泡显示状态改变时触发
  const popupVisibleChange = (val: boolean) => {
    if (val) {
      nextTick(() => {
        const el = document.getElementById('tableSetting') as HTMLElement;
        const sortable = new Sortable(el, {
          onEnd(e: any) {
            const { oldIndex, newIndex } = e;
            exchangeArray(cloneColumns.value, oldIndex, newIndex);
            exchangeArray(showColumns.value, oldIndex, newIndex);
          },
        });
      });
    }
  };

  // 多图预览
  const preview = () => {
    coverImgVisible.value = true;
  };

  // 已选择的数据行发生改变时触发 -- table 表头
  const selectionChange = (rowKeys: any[]) => {
    selectionKeys = rowKeys;
  };
  const selectMsg = (message?: string) => {
    Message.info(message || '请选择需要操作的数据');
  };
  // 批量删除
  const batchDel = () => {
    del(selectionKeys);
  };

  fetchData();
  getCategory();
</script>

<script lang="ts">
  export default {
    name: 'ModuleArticle',
  };
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }
  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
  .action-icon {
    margin-left: 12px;
    cursor: pointer;
    margin-bottom: -50px;
  }
  .active {
    color: #0960bd;
    background-color: #e3f4fc;
  }
  .setting {
    display: flex;
    align-items: center;
    width: 200px;
    .title {
      margin-left: 12px;
      cursor: pointer;
    }
  }
</style>
